﻿#-*-coding:utf-8-*-
from flask import Flask, request, session, jsonify,render_template
import os
import json
import requests
import logging


USERNAME='Master'
PASSWORD='123456'

app=Flask(__name__)


dir=os.path.dirname(__file__)
DDmsg_path=dir+'/DD_info'


# logo
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)

load_log_path = '/usr/MZ/Virtual/DingDingFlask/log/load.log'
pipline_log_path = '/usr/MZ/Virtual/DingDingFlask/log/pipline.log'
get_log_path = '/usr/MZ/Virtual/DingDingFlask/log/get.log'
post_log_path = '/usr/MZ/Virtual/DingDingFlask/log/post.log'








def debug_handler(logpath, msg):
    '''
    自定义log
    :param logpath:
    :param msg:
    :return:
    '''


    handler = logging.FileHandler(logpath, encoding='utf-8')
    handler.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(asctime)s - %(filename)s-line:%(lineno)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)


    logger.addHandler(handler)
    # self.logger.addHandler(console)

    logger.debug(msg)




def load_debug(msg):
    '''
    启动载入debug
    :param msg:
    :return:
    '''
    debug_handler(load_log_path,msg)



def pipline_debug(msg):
    '''
    流程debug
    :param msg:
    :return:
    '''
    debug_handler(pipline_log_path,msg)

def get_debug(msg):
    '''
    当获取到get请求时debug
    :param msg:
    :return:
    '''
    debug_handler(get_log_path,msg)


def post_debug(msg):
    '''
    当获取到post请求时debug
    :param msg:
    :return:
    '''
    debug_handler(post_log_path,msg)


























@app.route('/dd/')
def index():

    return "OK!"






def reformateData(data):
    '''
    过滤传来post数据
    :param data:
    :return:
    '''
    info=data['info']

    jsonData={}
    listData=[]

    for n in info:
        dic={}
        dic['Artist']=n[0]
        dic['Submit']=n[1]
        dic['Approve']=n[2]
        listData.append(dic)

    jsonData['back']=listData
    # pipline_debug("data过滤为:" + str(listData))
    return jsonData






def writeInfo(data):
    '''
    过渡函数，写入post来的数据
    :param data:
    :return:
    '''
    date=data['date']
    filepath=DDmsg_path+'/'+date

    if not os.path.exists(filepath):
        os.makedirs(filepath)

    txtPath=filepath+'/'+data['department']+'.json'
    with open(txtPath,'w',encoding='utf-8') as f:
        listData=reformateData(data)
        js=json.dumps(listData)
        f.write(js)
    # pipline_debug("data写入:"+txtPath)


#00000000000
# @app.route('/back/<data>',methods=['GET','POST'])#这种写法浪费了request的方法，其实还是直接获取的了参数
# def go(data):
#     if request.method=='GET':
#         return data
#     elif request.method=='POST':
#         #return date
#         newData=eval(data)
#         writeInfo(newData)
#         print(newData['department'])
#         return data
#     else:
#         return 'No'



@app.route('/upInfo/',methods=['GET','POST'])
def upInfo():
    '''
    当从timeaxis服务器传来post数据时，获取并存储到本地云服务器上
    :return:
    '''



    if request.method=='GET':
        return '查询失败'

    else:
        pipline_debug("post请求获取到数据data")
        data=request.data.decode('utf-8')
        # pipline_debug("data.decode(utf-8)成功")
        newData=eval(data)
        # pipline_debug("eval(data)成功")


        writeInfo(newData)
        # pipline_debug("data写入本地成功")
        return "haha"




def readTXT(date,department):
    '''
    过渡函数，读取txt文件内容，并返回
    :param date:
    :param department:
    :return:
    '''
    txtPath=DDmsg_path+'/'+date+'/'+department+'.json'

    backMsg=''
    # pipline_debug("开始获取数据")
    if not os.path.exists(txtPath):
        backMsg='{"back": [{"Artist": "没人提交", "Submit": 0, "Approve": 0}]}'
        # backMsg='No data'

    else:
        with open(txtPath,'r',encoding='utf-8') as r:
            backMsg=r.read()


    return backMsg




@app.route('/getInfo/',methods=['GET','POST'])
def getInfo():
    '''
    当从钉钉传来get请求时，获取服务器存储的信息
    :return:
    '''



    if request.method=="GET":
        date=request.args.get('date')

        department=request.args.get('department')
        # get_debug('请求日期：'+date+'请求部门：'+department)
        info=readTXT(date,department)
        # pipline_debug("获取存储信息返回："+info)
        return info

    else:
        #当时用post来请求内容，暂时不用
        pipline_debug('这是用post请求来获取云端数据')
        newdata=eval(request.data)
        date=newdata['date']
        department=newdata['department']
        # print('date:'+date)
        info=readTXT(date,department)
        return info













# @app.route('/login',methods =['GET','POST'])
# def login():
#     error = None
#     if request.method == 'POST':
#         if request.form['username'] != USERNAME:
#             error = 'Invalid username'
#         elif request.form['password'] != PASSWORD:
#             error = 'Invalid password'
#         else:
#             session['logged_in'] = True
#             return jsonify({'code': 200, 'msg': 'success'})
#     return jsonify({'code': 401, 'msg': error}), 401


#0000000
# @app.route('/dingding/<date>&<department>',methods =['GET','POST'])
# def dingdingGet(date,department):
#
#     txtPath=dir+'/'+date+'/'+department+'.txt'
#
#     backMsg=''
#
#     if not os.path.exists(txtPath):
#         backMsg=''
#     else:
#         with open(txtPath,'r',encoding='utf-8') as r:
#             backMsg=r.read()
#
#
#     return backMsg








#
# @app.route('/info', methods=['get'])
# def info():
#     if not session.get('logged_in'):
#         return jsonify({'code': 401, 'msg': 'please login !!'})
#     return jsonify({'code': 200, 'msg': 'success', 'data': 'info'})

# @app.route('/help/')
# def toDocument():
#     return render_template('index.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=8090,debug=True)